package com.ctl;

/**
 * @Version 1.0.0
 * @Author ctl
 * @Description
 * @Date 21-8-11 下午5:11
 */
/**
 * @Description:
 * @author: wei.wang
 * @since: 2020/9/4 19:42
 * @history: 1.2020/9/4 created by wei.wang
 */

import org.gjt.jclasslib.io.ClassFileWriter;
import org.gjt.jclasslib.structures.ClassFile;
import org.gjt.jclasslib.structures.Constant;
import org.gjt.jclasslib.structures.constants.ConstantStringInfo;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * 依赖jdk11  修改class常量内容
 */
public class ModifyClassConstant {
    public void say(){
        String temp="temp";
        String str="nihao "+temp+" !";
        System.out.println(str);
    }
    public static void main(String[] args) throws Exception {

        String filePath = "/home/ideaworkplace/gitee/util/ModifyClassConstant.class";
        FileInputStream fis = new FileInputStream(filePath);

        DataInput di = new DataInputStream(fis);
        ClassFile cf = new ClassFile();
        cf.read(di);

        Constant[] constantPool = cf.getConstantPool();

        int count = constantPool.length;
        System.out.println(count);

        for (int i = 0; i < count; i++) {
            if (constantPool[i] != null) {
                System.out.print(i);
                System.out.print(" = ");
                System.out.print(constantPool[i].getVerbose());
                System.out.print(" = ");
                try {
                    System.out.println(constantPool[i].getConstantType());
                } catch (Exception e) {
                 }
                //对23进行修改
                if(i == 2){
                    ConstantStringInfo uInfo = (ConstantStringInfo)constantPool[i];
                    uInfo.getUtf8Constant().setString("");
                    constantPool[i]=uInfo;
                }
            }
        }

        cf.setConstantPool(constantPool);
        fis.close();
        File f = new File(filePath);
        ClassFileWriter.writeToFile(f, cf);
    }
}